package com.yami.shop.mystery.common.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.event.EsMysteryBoxUpdateEvent;
import com.yami.shop.bean.event.MysteryBoxSoldOutEvent;
import com.yami.shop.mystery.common.dao.MysteryBoxOrderMapper;
import com.yami.shop.mystery.common.dao.MysteryBoxSkuMapper;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.model.MysteryBoxOrder;
import com.yami.shop.mystery.common.model.MysteryBoxSku;
import com.yami.shop.mystery.common.service.MysteryBoxService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author wxf
 * @date 2023/7/11 18:06
 */
@Component("mysteryBoxSoldOutListener")
@AllArgsConstructor
public class MysteryBoxSoldOutListener {

    private final MysteryBoxSkuMapper mysteryBoxSkuMapper;

    private final MysteryBoxOrderMapper mysteryBoxOrderMapper;

    private final MysteryBoxService mysteryBoxService;

    private final ApplicationEventPublisher eventPublisher;

    /**
     * 更新盲盒状态
     */
    @EventListener(MysteryBoxSoldOutEvent.class)
    public void mysteryBoxSoldOutListener(MysteryBoxSoldOutEvent event) {

        // 锁库存为0，库存为0，修改盲盒为售罄
        MysteryBoxSku sku = mysteryBoxSkuMapper.getByMysteryBoxId(event.getMysteryId());
        if (null == sku || sku.getStocks() > 0) {
            return;
        }

        List<MysteryBoxOrder> lockList = mysteryBoxOrderMapper.selectList(Wrappers.lambdaQuery(MysteryBoxOrder.class).eq(MysteryBoxOrder::getState, 0).eq(MysteryBoxOrder::getMysteryBoxId,event.getMysteryId()));
        if (CollectionUtils.isNotEmpty(lockList)) {
            return;
        }

        mysteryBoxService.update(Wrappers.lambdaUpdate(MysteryBox.class).eq(MysteryBox::getId, event.getMysteryId()).set(MysteryBox::getStatus, 4));
        eventPublisher.publishEvent(new EsMysteryBoxUpdateEvent(event.getMysteryId(), null, EsOperationType.UPDATE));
    }
}
